/** @format */

import { SchemaForm } from 'formvuelate'
import CompSlot from '@/form-pro/slot/Index.vue'
import { markRaw } from 'vue'

// setp1 初始化格式的数据

/**
 *
 * @param schema form 表单配置
 * @param theSlots form 表单中的插槽
 * @param theSchemaValue form 表单的值
 * @returns
 */

export function setComponentsDefaultCompSlot(
  schema: any,
  theSlots: any,
  theSchemaValue: any,
) {
  const theSchemaType = Object.prototype.toString.call(schema)

  // 判断传过来的值是对象还是数组
  if (theSchemaType === '[object Object]') {
    // 如果是对象
    return onInitObject(schema, theSlots, theSchemaValue)
  } else if (theSchemaType === '[object Array]') {
    // 如果是数组
    return onInitArray(schema, theSlots, theSchemaValue)
  } else {
    // 否则返回原值 -.- 等着报错吧
    return schema
  }
}
// setp2 初始化对象格式的数据
const onInitObject = (schema: any, theSlots: any, theSchemaValue: any) => {
  Object.keys(schema).forEach((key) => {
    // schema[key].ifInnerShow = false
    // 如果存在 ifShow 函数给ifShow函数传值 并校验是否显示
    if (schema[key]?.ifShow) {
      // 为重复赋值 将 ifShow 传给子组件改为 isShow
      schema[key].ifInnerShow = schema[key].ifShow({
        schema,
        value: theSchemaValue,
      })
    }

    if (schema[key].components === 'Children') {
      schema[key].component = markRaw(SchemaForm)
      onInitObject(schema[key].schema, theSlots, theSchemaValue)
    } else if (schema[key].components === 'Slot') {
      // 组件组要在这里赋值 start
      schema[key].component = markRaw(CompSlot)
      if (theSlots != 'noRefresh') {
        schema[key].slots = theSlots
      }
      // 组件组要在这里赋值 end
    } else {
      schema[key].component = CompSlot
    }
  })
  // console.log('schema ===>',schema);

  return schema
}

// setp3 初始化数组格式的数据
const onInitArray = (schema: any, theSlots: any, theSchemaValue: any) => {
  Object.keys(schema).forEach((key) => {
    schema[key] = onInitObject(schema[key], theSlots, theSchemaValue)
  })
  return schema
}

// 判断是什么类型 start
export enum THE_SCHEMA_TYPE {
  OBJECT = 'object',
  ARRAY = 'array',
  OTHER = 'other',
}
export const getSchemaType = (data: any) => {
  var type = ''
  if (Object.prototype.toString.call(data) === '[object Object]') {
    type = THE_SCHEMA_TYPE.OBJECT
  } else if (Object.prototype.toString.call(data) === '[object Array]') {
    type = THE_SCHEMA_TYPE.ARRAY
  } else {
    type = THE_SCHEMA_TYPE.OTHER // 不知道什么类型
  }
  return type
}
// 判断是什么类型 end
